from flask import request,abort,current_app,make_response,jsonify,jsonify
from flask import session

from info import redis_store,constants,db
from info.utils.captcha.captcha import captcha
from . import passport_blu
import random
import re
from info.utils.response_code import RET
from . import passport_blu
from info.libs.yuntongxun.sms import CCP
from info.models import User
from datetime import datetime
from info.utils.captcha_test.captcha import generate_code




@passport_blu.route('/image_code')
def generate_image_code():

    image_code_id = request.args.get('code_id')

    if not image_code_id:
        abort(403)

    name,text,image = captcha.generate_captcha()
    text,image = generate_code()
    print('图片验证码是：{}'.format(text))

    try:
        redis_store.setex('ImageCode_' + image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)
    except Exception as e:
        current_app.logger.error(e)




    response = make_response(image)
    response.headers['Content-Type'] = 'image/png'

    return response

@passport_blu.route('/sms_code',methods=['POST'])
def send_sms_code():
    json_data = request.json
    mobile = json_data.get('mobile')
    image_code = json_data.get('image_code')
    image_code_id = json_data.get('image_code_id')

    if not all([mobile,image_code,image_code_id]):
        return  jsonify(erron = RET.PARAMERR,errmsg='参数不全')

    if not re.match('^1[3578][0_9]$',mobile):
        return jsonify(eerno=RET.DATAERR,errmsg='手机号不正确')

    try:
        real_image_code = redis_store.get('ImageCode_'+image_code_id)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errms='数据库查询错误')
    if not real_image_code:
         return jsonify(errno=RET.DBERR,errmsg='验证码已过期')
    # if real_image_code.lower() != image_code.lower():
    num1 = int(real_image_code[:1])
    num2 = int(real_image_code[2:3])
    num = num1+num2
    if num != int(image_code):
        return jsonify(errno=RET.DATAERR,errmsg='验证码输入错误')

    try:
        user = User.query.filter(User.mobile == mobile).first()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询错误')

    if user:
        return jsonify(errno=RET.DATAEXIST,eremsg='该手机号已被注册')


    result = random.randint(0.999999)
    sms_code = '%06d' % result
    print('短信验证码是：{}'.format(sms_code))

    result = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], "1")
    # if result != 0:
    #     return jsonify(errno=RET.THIRDERR, errmsg="发送短信失败")
    try:
        redis_store.set('SMS_'+mobile,sms_code,constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='手机验证码保存失败')


    return jsonify(errno=RET.OK, errmsg="发送成功")


@passport_blu.route('register',methods=['POST'])
def register():
    json_data = request.json
    mobile = json_data.get('mobile')
    smscode = json_data.get('smscode')
    password = json_data.get('password')

    if not all([mobile,smscode,password]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')
    if not re.match("^1[3578][0-9]{9}$", mobile):
        return jsonify(errno=RET.DATAERR, errmsg="手机号不正确")

    try:
        real_sms_code = redis_store.get("SMS_" + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="手机验证码过期")

    if real_sms_code != smscode:
        return jsonify(errno=RET.DATAERR, errmsg="输入的手机验证码不正确")

    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    user.password = password
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

    # 由于注册后，自动登陆，需要保存用户登陆状态，通过session来设置
    session["user_id"] = user.id

    return jsonify(errno=RET.OK, errmsg="注册成功")



@passport_blu.route('/login',methods = ['POST'])
def login():
    json_data = request.json
    mobile = json_data.get("mobile")
    # 用户输入的明文密码
    password = json_data.get("password")

    if not re.match("^1[3578][0-9]{9}$", mobile):
        return jsonify(errno=RET.DATAERR, errmsg="手机号不正确")

    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="该手机号没有注册")

    if not user.check_passowrd(password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")

    # 走到这一步说明登陆成功
    session["user_id"] = user.id

    # 因为注册已经默认过登陆，所以登陆时间已经存在，我们需要去设置最后一次登陆的时间
    user.last_login = datetime.now()

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")

    return jsonify(errno=RET.OK, errmsg="登陆成功")



@passport_blu.route('/logout')
def logout():
    """
    目的是清除session
    :return:
    """

    session.pop('user_id',None)
    return jsonify(errno=RET.OK,errmsg='ok')













